﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _使用参数化执行SQL语句
{
    public partial class Form1 : Form
    {
        public List<string> SqlWhere { get; set; }

        public List<SqlParameter> SqlPara { get; set; }

        public List<int> Numbers;


        public Form1()
        {
            InitializeComponent();
            InitEvent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //绑定数据
            BdingData();
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BdingData()
        {
            if (SqlWhere == null)
            {
                SqlWhere = new List<string>();
            }
            if (SqlPara == null)
            {
                SqlPara = new List<SqlParameter>();
            }
            string sqlStr = "Select top 50 * from Student where 1=1 " + string.Join(" ", SqlWhere.ToArray()) + " Order By CreateDate Desc";
            dataGridView1.DataSource = SqlUtil.GetList<tbl_Person>(WebConfig.DefaultConfigString, CommandType.Text, sqlStr, SqlPara.ToArray());
        }

        /// <summary>
        /// 初始化事件
        /// </summary>
        public void InitEvent()
        {
            btnSearch.Click += new EventHandler(btnSearch_Click);
        }

        /// <summary>
        /// 单击查询时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnSearch_Click(object sender, EventArgs e)
        {
            GetWhere();
            BdingData();
        }

        public void GetWhere()
        {
            if (SqlWhere == null)
            {
                SqlWhere = new List<string>();
            }
            else
            {
                SqlWhere.Clear();
            }
            if (SqlPara == null)
            {
                SqlPara = new List<SqlParameter>();
            }
            else
            {
                SqlPara.Clear();
            }

            string StuName = txtStuName.Text;
            string StuNum = txtStuNum.Text;
            string StuSex = txtStuSex.Text;
            if (!string.IsNullOrEmpty(StuName))
            {
                SqlWhere.Add(" and Name like @StuName");
                SqlPara.Add(new SqlParameter("@StuName", "%" + StuName + "%"));
            }

            if (!string.IsNullOrEmpty(StuNum))
            {
                SqlWhere.Add(" and StuNum=@StuNum");
                SqlPara.Add(new SqlParameter("@StuNum", StuNum));
            }

            if (!string.IsNullOrEmpty(StuSex))
            {
                SqlWhere.Add(" and Sex=@StuSex");
                SqlPara.Add(new SqlParameter("@StuSex", StuSex));
            }
        }

    }
}
